import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"];

// 前置守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start();

  // 获取token
  const token = store.getters.token;
  // 获取用户名
  const name = store.getters.name;

  if (token) {
    if (to.path === "/login") {
      next({ path: '/' });
      NProgress.done();
    } else {
      next();
      if (!name) {
        store.dispatch("user/userInfoActions");
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next(); // 如果访问的是白名单直接放心
    } else {
      // 访问的不是白名单  则去登录页
      next("/login");
      NProgress.done();
    }
  }
  next();
});

router.afterEach((to) => {
  // finish progress bar
  document.title = getPageTitle(to.meta.title);
  NProgress.done();
});
